package com.bayss.core.service;

import com.bayss.core.entity.rbac.OBGPermissionsInfo;
import com.bayss.core.entity.rbac.OBGUserInfo;
import com.bayss.core.entity.rbac.ObgOperateLog;
import com.bayss.core.entity.rbac.ObgOperateLogExample;
import com.bayss.core.entity.rbac.mapper.OBGUserInfoMapper;
import com.bayss.core.entity.rbac.mapper.ObgOperateLogMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Created by LDL on 2020/1/5.
 */
@Service
public class OperateLogService {
    private static Logger logger = LogManager.getLogger();
    @Autowired
    private ObgOperateLogMapper obgOperateLogMapper;
    @Autowired
    private PermissionsService permissionsService;
    @Autowired
    private OBGUserInfoMapper obgUserInfoMapper;

    /**
     * 保存操作记录（异步）
     *
     * @param userId
     * @param url
     */
    @Async
    public void saveOperateLog(Integer userId, String url) {
        ObgOperateLog operateLog = new ObgOperateLog();
        operateLog.setUrl(url);
        operateLog.setUserId(userId);
        OBGPermissionsInfo p = permissionsService.findPermissionsByUrl(url);
        if (p != null) {
            OBGPermissionsInfo parent = permissionsService.findById(p.getParentId());
            operateLog.setResourceName("【" + parent.getName() + "】-【" + p.getName() + "】");
        }
        logger.info("userId:{},operate:{}", userId, operateLog.getResourceName());
        obgOperateLogMapper.insertSelective(operateLog);
    }


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageInfo<ObgOperateLog> listPages(ObgOperateLog query, int page, int pageSize) {
        ObgOperateLogExample example = new ObgOperateLogExample();
        ObgOperateLogExample.Criteria criteria = example.createCriteria();

        example.setOrderByClause("create_time desc");
        PageInfo<ObgOperateLog> result = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> obgOperateLogMapper.selectByExample(example));
        for (ObgOperateLog e : result.getList()) {
            OBGUserInfo userInfo = obgUserInfoMapper.selectByPrimaryKey(e.getUserId());
            e.setNickName(userInfo == null ? "" : userInfo.getNickname());
        }
        return result;
    }
}
